/**
 * Created by isoft-work 5 on 12/20/2014.
 */
$(document).ready(function(){
//   render
   renderUserCartPage();
//   event
});

function renderUserCartPage() {
   getListCartPage();
}

function getListCartPage(){
   ISS.BACKEND.request({
      url: ISS.SESSION.getSession('contextPath') + '/service/product/getListCart',
      type: 'GET',
      success: function (data) {
         var responseInfo = data.responseObject;
         changePriceToString(responseInfo);
         mapListCartPageToView(responseInfo);
      }
   });
}

function mapListCartPageToView(shopCart) {
   shopCart.contextPath = ISS.SESSION.getSession('contextPath');
   var _htmlItem = ISS.TEMPLATE.handleBar.renderByString(TEMPLATE.CartPage.cartItem ,shopCart);
   delete shopCart.contextPath;
   ISS.DOM.html('#cart_item_list', _htmlItem);
   ISS.DOM.html('#cart_page_all_total', shopCart.total);
   ISS.DOM.html('#cart_page_all_money', ISS.STRING_UTIL.formatNumeral(shopCart.totalMoney, '0,0') + '&nbsp;VND');
   // event
   bindEventCartPage(shopCart.carts);
}

function bindEventCartPage(carts) {
   for(var i = 0; i < carts.length; i++) {
      // remove cart
      ISS.EVENT.bindEvent('#cart_delete_' + carts[i].chiTietSanPham.maCTSP, 'click', function () {
         var _id = ISS.DOM.getData(this,'id');

         ISS.BACKEND.request({
            url: ISS.SESSION.getSession('contextPath') + '/service/product/deleteCart/' + _id,
            type: 'GET',
            success: function (data) {
               var responseInfo = data.responseObject;
               removeUpdateCartComplete(responseInfo);
            }
         });
      });
      // update cart
      ISS.EVENT.bindEvent('#cart_update_' + carts[i].chiTietSanPham.maCTSP, 'blur', function () {
         var _id = ISS.DOM.getData(this,'id');
         var _num = ISS.DOM.getVal('#'+this.id) ? ISS.DOM.getVal('#'+this.id) : '1';

         ISS.BACKEND.request({
            url: ISS.SESSION.getSession('contextPath') + '/service/product/updateCart/' + _id + '/' +_num,
            type: 'GET',
            success: function (data) {
               var responseInfo = data.responseObject;
               if(data.code == 0) {
                  removeUpdateCartComplete(responseInfo);
               }
               else {
                  alert('Không đủ số lượng !');
               }
            }
         });
      });

      // validate input

      ISS.EVENT.bindEvent('#cart_update_' + carts[i].chiTietSanPham.maCTSP, 'keypress', function (e) {
         ISS.VALIDATION.allowInput(e, /[0-9]/);
      });
   }
}

function removeUpdateCartComplete(listCart){
   changePriceToString(listCart);
   mapListCartPageToView(listCart);
   mapCartToView(listCart);
}
